package edu.usc.cmb.iregulome.client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

public class ResultUploadExample {

	/**
	 * @param args
	 * @throws IOException
	 */
	public static void main(String[] args) throws IOException {

		Connection connection = null;
		try {
			// Load the JDBC driver
			String driverName = "org.gjt.mm.mysql.Driver"; // MySQL MM JDBC
			// driver
			Class.forName(driverName);

			// Create a connection to the database
			String serverName = "zhoudb.usc.edu";
			String mydatabase = "seq_db";
			String url = "jdbc:mysql://" + serverName + "/" + mydatabase; // a
			// JDBC
			// url
			String username = "siyuanh";
			String password = "11";
			connection = DriverManager.getConnection(url, username, password);

			String sql = "INSERT INTO ChIPseqPeaks VALUES(?,?,?,?,?,?,?)";
			PreparedStatement peakPreStat = connection.prepareStatement(sql);

			BufferedReader br = new BufferedReader(
					new InputStreamReader(
							ClassLoader
									.getSystemResourceAsStream("example.binding.positions.txt")));
			String lineString = br.readLine();
			int count = 0;
			while (lineString != null) {
				if (count == 0) {
					count++;
					lineString = br.readLine();
					continue;
				}
				String[] fields = lineString.split("[\t| ]+?");
				peakPreStat.setString(1, fields[0]);
				peakPreStat.setInt(2, Integer.parseInt(fields[1]));
				peakPreStat.setInt(3, Integer.parseInt(fields[1]));
				peakPreStat.setFloat(4, Float.parseFloat(fields[3]));
				peakPreStat.setFloat(5, -1);
				peakPreStat.setFloat(6, Float.parseFloat(fields[4]));
				peakPreStat.setString(7, "SRS002716");
				peakPreStat.addBatch();
				lineString = br.readLine();
				count++;
			}

//			peakPreStat.executeBatch();

			sql = "INSERT INTO ChIPseqBroadPeaks VALUES(?,?,?,?,?,?,?)";
			peakPreStat = connection.prepareStatement(sql);
			br = new BufferedReader(new InputStreamReader(ClassLoader
					.getSystemResourceAsStream("example.broadPeak")));
			lineString = br.readLine();
			while (lineString != null) {

				String[] fields = lineString.split("[\t| ]+?");
				for (String string : fields) {
					System.out.println(string);
				}
				peakPreStat.setString(1, fields[0]);
				peakPreStat.setInt(2, Integer.parseInt(fields[1]));
				peakPreStat.setInt(3, Integer.parseInt(fields[2]));
//				peakPreStat.setInt(3, NumberFormat.getInstance().parse(fields[2]).intValue());
				peakPreStat.setFloat(4, Float.parseFloat(fields[6]));
				peakPreStat.setFloat(5, -1);
				peakPreStat.setFloat(6, -1);
				peakPreStat.setString(7, "SRS002716");
				peakPreStat.addBatch();
				lineString = br.readLine();

			}

			peakPreStat.executeBatch();
			connection.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}
